package com.yupi.springbootinit.service.impl;

import cn.hutool.extra.pinyin.PinyinUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yupi.springbootinit.autocommit.AutoCommitContext;
import com.yupi.springbootinit.autocommit.DbType;
import com.yupi.springbootinit.autocommit.KBEnum;
import com.yupi.springbootinit.exception.AutoCommitSelfException;
import com.yupi.springbootinit.model.dto.autoCommit.AutoCommitRequest;
import com.yupi.springbootinit.service.ClientInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class ClientInfoServiceImpl implements ClientInfoService {
    private static final String E10_BASE_URL = "https://www.e-cology.com.cn/";
    private static final String CLIENT_INFO_URI = "api/secondev/cm/customerSysRecord/getBaseInfoFormItem?isE10=0&id=0&customerId=";

    @Value("${weaver.eteamsid:null}")
    private String eteamsId;

    public String getEteamsId() {
        return eteamsId;
    }

    public void setEteamsId(String eteamsId) {
        this.eteamsId = eteamsId;
    }

    private JSONObject remoteGet(AutoCommitRequest autoCommitrequest) throws AutoCommitSelfException {
        String url = E10_BASE_URL + CLIENT_INFO_URI + autoCommitrequest.getCustomerId();
        // 设置需要传递的 Cookie 信息
        eteamsId = autoCommitrequest.getEteamsId() == null?eteamsId:autoCommitrequest.getEteamsId();
        String result = getString(eteamsId, url);
        JSONObject jsonObject = JSONObject.parseObject(result);
        if ("-1".endsWith(jsonObject.get("code").toString())) {
            throw new AutoCommitSelfException("ETEAMSID过期，需要重置");
        }
        return jsonObject;
    }

    private static String getString(String  eteamsId, String url) {
        HttpRequest request = HttpRequest.get(url)
                .header("Cookie", "ETEAMSID=" +eteamsId); // 替换为实际的 Cookie 名称和值

        // 发送 GET 请求并获取响应
        HttpResponse response = request.execute();
        // 处理响应内容
        String result = response.body();
        return result;
    }

    @Override
    public AutoCommitContext initAutoCommitContext(AutoCommitRequest autoCommitrequest) throws AutoCommitSelfException {


        try {
            JSONObject jsonObject = remoteGet(autoCommitrequest);
            JSONObject dataObj = JSONObject.parseObject(JSONObject.toJSONString(jsonObject.get("data")));
            JSONObject itemObj = JSONObject.parseObject(JSONObject.toJSONString(dataObj.get("items")));

            String svnpath = autoCommitrequest.getProjectUrl();

            String filepath = autoCommitrequest.getClientBakFilePath();
            DbType dbType = autoCommitrequest.getDbType();
            KBEnum kbEnum = autoCommitrequest.getKb();
            if (svnpath == null) {
                JSONObject svnpathObj = JSONObject.parseObject(JSONObject.toJSONString(itemObj.get("svnpath")));
                svnpath = svnpathObj.get("value").toString();
                if (svnpath.contains(";")) {
                    String[] split = svnpath.split(";");
                    for (String path : split) {
                        if (!path.endsWith("obile/")) {
                            svnpath = path;
                            break;
                        }
                    }
                }
            }
            if (filepath == null) {
                JSONObject hisFilePathObj = JSONObject.parseObject(JSONObject.toJSONString(itemObj.get("hisFilePath")));
                filepath = hisFilePathObj.get("value").toString();
            }
            if (dbType == null) {
                JSONObject dbVersionIdObj = JSONObject.parseObject(JSONObject.toJSONString(itemObj.get("dbVersionId")));
                JSONArray dbValues = JSONArray.parseArray(JSONArray.toJSONString(dbVersionIdObj.get("value")));
                String dbConent = JSONObject.parseObject(JSONObject.toJSONString(dbValues.get(0))).get("content").toString();
                dbType = parseDbType(dbConent);
            }
            if (kbEnum == null) {
                JSONObject patchVersionIdObj = JSONObject.parseObject(JSONObject.toJSONString(itemObj.get("patchVersionId")));
                JSONArray kbValues = JSONArray.parseArray(JSONArray.toJSONString(patchVersionIdObj.get("value")));
                String kbContent = JSONObject.parseObject(JSONObject.toJSONString(kbValues.get(0))).get("content").toString();
                try {
                    kbEnum = KBEnum.valueOf(kbContent);
                } catch (Exception e) {

                    if (kbContent.startsWith("KB")) {
                        String kb = kbContent.replace("KB", "");
                        Long aLong = Long.getLong(kb, -1L);
                        if (aLong > 900240102L) {
                            kbEnum = KBEnum.HighKb;
                        }
                    }
                    if (kbEnum == null) {
                        throw new AutoCommitSelfException("kb解析异常:需要确认客户是否2310版本，或者手动指定版本号，当前客户kb信息：" + kbContent);
                    }
                }
            }
            return new AutoCommitContext(svnpath, filepath, kbEnum, dbType);
        } catch (AutoCommitSelfException overDue) {
            throw overDue;
        } catch (Exception e) {
            throw new RuntimeException("通过自用系统爬取客户信息失败，,需要手动填写客户的kb，数据库缩写，内网地址和备案环境地址");
        }
    }

    public DbType parseDbType(String content) {
        if (content.startsWith("SQL")) {
            return DbType.SQLServer;
        }
        if (content.startsWith("Oracle")) {
            return DbType.Oracle;
        }
        if (content.contains("达梦") || content.startsWith("DM") || content.startsWith("dm")) {
            return DbType.DM;
        }
        if (content.toLowerCase().contains("mysql")) {
            return DbType.Mysql;
        }
        if (content.toLowerCase().contains("pg") || content.toLowerCase().contains("postgresql")) {
            return DbType.PG;
        }
        if (content.contains("神通")) {
            return DbType.ST;
        }
        if (content.contains("人大")) {
            return DbType.JC;
        }
        if (content.contains("GS") || PinyinUtil.getFirstLetter(content, "").contains("gs")) {
            return DbType.GS;
        }
        log.warn("数据库解析失败：{}", content);
        return null;
    }
}
